import { Key, memo, useCallback, useEffect, useRef, useState } from "react";
import {
  BaseContiner,
  FlexContainer,
  LeftContainer,
  RightContainer,
  TableContainer,
  TableHeader,
} from "../../../csscomponents/base";
import UnitTree from "../../../components/unit-tree";
import {
  Button,
  Col,
  Flex,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tooltip,
  message,
} from "antd";
import { ErrorBox } from "../../../components/error-box";
import { SearchOutlined, PlusOutlined } from "@ant-design/icons";
import { IFormRef, IRoleRestFillRefHandler } from "../../../types";
import { useForm } from "antd/es/form/Form";
import { useRecoilState } from "recoil";
import { userState } from "../../../stores/user";
import {
  IBeef,
  IBeefSearchParams,
  decrypt,
  useDeletedBeefById,
  useGetBeefBySearch,
} from "../../../service/beef/beef-service";
import BeefForm from "./beef-form";
import { useGetBeefType } from "../../../service/beef-type-service";
import BeefRisk from "./beef-risk";
import BeefSloveStepForm from "./beef-solve-setp-form";
import { exportExcel } from "xlsx-oc";
import { request, useRequest } from "../../../utils/request";

const BeefPage = () => {
  const [sys] = useRecoilState(userState);
  const [open, setOpen] = useState<boolean>(false);
  const [openRisk, setOpenRisk] = useState<boolean>(false);
  const [openBeefSolveStep, setOpenBeefSolveStep] = useState<boolean>(false);
  //需要修改的矛盾纠纷
  const [update, setUpdate] = useState<IBeef>();

  //需要修改的风险评估的矛盾纠纷ID
  const [beefId, setBeefId] = useState<string>();

  const [beefIdSlove, setBeefIdSlove] = useState<string>();
  const [isEdit ,setIsedit] = useState<number>(0)

  //单位引用
  const unitTreeRef = useRef<IRoleRestFillRefHandler>();
  const [queryForm] = useForm();
  const defaultData: IBeefSearchParams = {
    page: 1,
    limit: 10,
    unitId: sys.userInfo.unitId || "",
    beefName: "",
    xm: "",
    phone: "",
    certificateNumber: "",
    beefType: null,
    status: null,
    startTime: "",
    endTime: "",
    beefSource: null,
    userName: "",
  };
  const [queryParams, setQueryParams] =
    useState<IBeefSearchParams>(defaultData);

  const FormRef = useRef<IFormRef>();
  const [exportLoading, setExportLoading] = useState<boolean>(false);
  const request = useRequest<string>();
  //导出
  const exportXq = () => {
    if (!checkAll && selectKeys.length == 0) {
      message.error("请选择需要下载的项");
      return;
    }
    setExportLoading(true);
    const downLoadData = {
      isAllChecked: checkAll ? 1 : 2,
      selectKeys: selectKeys,
      unSelectKeys: unSelectKeys,
      ...queryParams,
    };
    request("/beef/exportExcel", {
      data: { ...downLoadData },
      json: true,
      method: "POST",
    })
      .then((res: any) => {
        res.forEach((element: any, i: number) => {
          element.index = i + 1 + "";
          if (element.userSex === "1") {
            element.userSex = "男";
          } else if (element.userSex === "2") {
            element.userSex = "女";
          } else {
            element.userSex = "";
          }
          if (element.beefSource === 1) {
            element.beefSource = "走访";
          } else if (element.beefSource === 2) {
            element.beefSource = "矛排";
          } else {
            element.beefSource = "";
          }
          if (element.isZu === 1) {
            element.isZu = "是";
          } else if (element.isZu === 2) {
            element.isZu = "否";
          } else {
            element.isZu = "";
          }
          element.phone = decrypt(element.phone);
          element.certificateNumber = decrypt(element.certificateNumber);
        });

        const header: { k: string; v: string }[] = [
          { v: "序号", k: "index" },
          { v: "类型", k: "beefSource" },
          { v: "被走访人姓名", k: "xm" },
          { v: "被走访人电话", k: "phone" },
          { v: "被走访人号码", k: "certificateNumber" },
          { v: "被走访人性别", k: "userSex" },
          { v: "地址", k: "beefAddress" },
          { v: "所属派出所", k: "unitName" },
          { v: "是否租户", k: "isZu" },
          { v: "房东姓名", k: "houseUserName" },
          { v: "房东电话号码", k: "houseUserPhone" },
          { v: "租房开始时间", k: "startTime" },
          { v: "租房结束时间", k: "endTime" },
          { v: "走访类型", k: "zfType" },
          { v: "入录人", k: "sysName" },
        ];
        setExportLoading(false);
        const fileName = "导出.xlsx";
        exportExcel(header, res, fileName);
        setExportLoading(false);
      })
      .catch((e) => {
        message.error("下载出错了");
        setExportLoading(false);
      });
  };

  /**单位选中回调 */
  const getCheckUnit = (unitId: string) => {
    if (unitId && unitId !== queryParams.unitId) {
      setQueryParams({ ...queryParams, unitId: unitId });
    }
  };
  /**
   * 重置搜索
   */
  const resetQueryParams = () => {
    setQueryParams(defaultData);
    unitTreeRef.current?.rest();
    queryForm.resetFields();
  };

  /**搜索单位 */
  const searchData = (value: Omit<IBeefSearchParams, "page" | "limit">) => {
    setQueryParams({
      ...queryParams,
      ...value,
      page: 1,
      limit: 10,
    });
  };

  /**
   * !获取矛盾纠纷Hook
   */
  const {
    isLoading,
    isError,
    data: dataSource,
    error,
    refetch,
  } = useGetBeefBySearch(queryParams);
  /**
   * !删除矛盾纠纷HOOK
   */
  const { mutateAsync: deleteMutation, isLoading: DIsLoading } =
    useDeletedBeefById();
  /**
   * 打开基本信息form
   */
  const openFn = useCallback((open: boolean) => {
    setOpen(open);
  }, []);

  /**
   * 关闭风险评估
   */
  const closeBeefRiskFn = useCallback((open: boolean) => {
    setOpenRisk(open);
    setBeefId(undefined);
  }, []);

  const { data: dataSourceBeefType } = useGetBeefType({
    beefTypeName: "",
    page: 1,
    limit: -1,
  });

  const openRiskDrawHandler = (beefId: string) => {
    setBeefId(beefId);
    setOpenRisk(true);
  };

  const closeBeefSolveStepHandler = useCallback((open: boolean) => {
    setOpenBeefSolveStep(false);
    setBeefId(undefined);
  }, []);
  const columns = [
    {
      title: "类型",
      dataIndex: "beefSource",
      render(beefSource: number) {
        if (beefSource === 1) {
          return "110警情";
        } else if (beefSource === 2) {
          return "矛盾纠纷自排查";
        }
      },
    },
    {
      title: '事件名称',
      dataIndex: 'beefName',
    },
    {
      title: '归属网络',
      dataIndex: 'belongNetwork',
    },
    {
      title: '走访地址',
      dataIndex: 'beefAddress',
    },
    {
      title: "风险等级",
      dataIndex: "riskLevel",
      render(riskLevel: string, obj: IBeef) {
        if (riskLevel === "0") {
          return (
            <Button
              type={"link"}
              onClick={() => {
                openRiskDrawHandler(obj.beefId);
              }}
            >
              待评估
            </Button>
          );
        } else if (riskLevel === "1") {
          return (
            <Button
              type={"default"}
              onClick={() => {
                openRiskDrawHandler(obj.beefId);
              }}
            >
              一般类
            </Button>
          );
        } else if (riskLevel === "2") {
          return (
            <Button
              type={"primary"}
              onClick={() => {
                openRiskDrawHandler(obj.beefId);
              }}
            >
              关注类
            </Button>
          );
        } else if (riskLevel === "3") {
          return (
            <Button
              danger
              onClick={() => {
                openRiskDrawHandler(obj.beefId);
              }}
            >
              重点类
            </Button>
          );
        }
      },
    },
    // {
    //     title: '纠纷类型',
    //     dataIndex: 'beefType',
    //     render(beefType: number) {
    //         const arr = dataSourceBeefType?.list.filter(e => e.beefTypeId === beefType);
    //         if (arr && arr.length > 0) {
    //             return arr[0].beefTypeName
    //         }
    //     }
    // },
    // {
    //     title: '纠纷详情',
    //     dataIndex: 'beefDetail',
    //     width: "200px",
    //     render(beefDetail: string) {
    //         return <Tooltip title={beefDetail}>
    //             <span>{beefDetail && beefDetail.length > 30 ? beefDetail.substring(0, 38) + '...' : beefDetail}</span>
    //         </Tooltip>
    //     }
    // },
    {
      title: "流程状态",
      dataIndex: "status",
      render(status: number, project: IBeef) {
        return (
          <Button
            type={"link"}
            onClick={() => {
              setBeefIdSlove(project.beefId);
              setOpenBeefSolveStep(true);
            }}
          >
            {" "}
            查看
          </Button>
        );
      },
    },
    {
      title: "更多操作",
      render(project: IBeef) {
  
          {
            if( sys.userInfo.sysId == project.beefFlowUserId){
              return(
          <div>
            <Button
              style={{ marginRight: "1.2rem" }}
              onClick={() => {
                setUpdate(project);
                setIsedit(2);
                setOpen(true);
              }}
            >
              修改
            </Button>
            <Button
              loading={DIsLoading}
              danger
              onClick={() => removeHandler(project.beefId)}
            >
              删除
            </Button>
          </div>
              )
            }else{
              return(
                <div>
              <Button
              onClick={() => {
                setUpdate(project);
                setIsedit(1);
                setOpen(true);
              }}
            >
              查看
            </Button>
                </div>
              )
            }
          }


      },
    },
  ];

  /**
   * 分页配置
   */
  const paginationProps = {
    total: dataSource?.count,
    pageSize: queryParams.limit,
    current: queryParams.page,
    showTotal: (count: number) => {
      return `共 ${count} 条`;
    },
    onChange: (pageNum: number) => {
      setQueryParams({ ...queryParams, page: pageNum });
    },
  };
  /**删除 */
  const removeHandler = (beefId: string) => {
    Modal.confirm({
      title: "⚠️警告",
      content: "你确认执行改操作吗?",
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        await deleteMutation({ beefId });
        refetch();
      },
    });
  };
  /**
   * table 选中的事件
   */
  const tableSelect = (record: IBeef, selected: boolean) => {
    if (selected) {
      setSelectKeys([...selectKeys, record.beefId]);
      if (unSelectKeys.indexOf(record.beefId) !== -1) {
        unSelectKeys.splice(unSelectKeys.indexOf(record.beefId), 1);
      }
    } else {
      setunSelectKeys([...unSelectKeys, record.beefId]);
      selectKeys.splice(selectKeys.indexOf(record.beefId), 1);
      setSelectKeys([...selectKeys]);
    }
  };
  /**
   * table 选中的 keys
   */
  const [selectKeys, setSelectKeys] = useState<Key[]>([]);
  /**
   * 手动剔除的选项
   */
  const [unSelectKeys, setunSelectKeys] = useState<Key[]>([]);

  /**
   * table 全选的事件
   */
  const [checkAll, setCheckAll] = useState<boolean>(false);
  useEffect(() => {
    if (checkAll) {
      const keys: string[] = [];
      const data: IBeef[] = dataSource?.list || [];
      data.forEach((element) => {
        if (unSelectKeys.indexOf(element.beefId) === -1) {
          keys.push(element.beefId);
        }
      });
      setSelectKeys(keys);
    } else {
      setSelectKeys([]);
    }
  }, [checkAll, dataSource, unSelectKeys]);
  const tableSelectAll = (selected: boolean) => {
    if (selected) {
      setCheckAll(true);
    } else {
      setCheckAll(false);
    }
  };
  return (
    <FlexContainer>
      <LeftContainer>
        <UnitTree getCheckUnit={getCheckUnit} onRef={unitTreeRef} />
      </LeftContainer>
      <RightContainer>
        <BaseContiner>
          <TableHeader>
            <Form
              onFinish={searchData}
              name="unit_search_form"
              style={{ width: "100%" }}
              form={queryForm}
            >
              <Row gutter={16}>
                <Col span={5}>
                  <Form.Item label="当事人姓名" name={"xm"}>
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={5}>
                  <Form.Item label="当事人电话" name={"phone"}>
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={5}>
                  <Form.Item label={"类型"} name={"beefSource"}>
                    <Select
                      options={[
                        { value: 1, label: "110警情" },
                        { value: 2, label: "矛盾纠纷自排查" },
                      ]}
                      allowClear
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item>
                    <Space>
                      <Button
                        type="primary"
                        htmlType="submit"
                        icon={<SearchOutlined />}
                      >
                        搜索
                      </Button>
                      <Button type="primary" onClick={() => resetQueryParams()}>
                        重置
                      </Button>
                      <Button
                        type={"primary"}
                        icon={<PlusOutlined />}
                        onClick={(event: any) => {
                          setOpen(true);
                          setUpdate(event);
                          setIsedit(0);
                        }}
                      >
                        添加
                      </Button>
                      {/* <Button
                        type="primary"
                        danger
                        onClick={() => exportXq()}
                        loading={exportLoading}
                      >
                        导出
                      </Button> */}
                    </Space>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </TableHeader>
          <TableContainer>
            {isError ? (
              <ErrorBox error={error as { message: string }} />
            ) : (
              <Table
                dataSource={dataSource?.list}
                rowSelection={{
                  type: "checkbox",
                  onSelect: tableSelect,
                  onSelectAll: tableSelectAll,
                  selectedRowKeys: selectKeys,
                }}
                columns={columns}
                loading={isLoading}
                pagination={paginationProps}
                rowKey={(row) => row?.beefId}
              />
            )}
          </TableContainer>
        </BaseContiner>
        <BeefForm
          open={open}
          onRef={FormRef}
          openFn={openFn}
          refetch={refetch}
          beef={update}
          isEdit={isEdit}
          setUpdate={setUpdate}
        />
        {/* <BeefRisk
          open={openRisk}
          setOpen={closeBeefRiskFn}
          beefId={beefId}
          refetch={refetch}
        /> */}
        <BeefSloveStepForm
          open={openBeefSolveStep}
          setOpen={closeBeefSolveStepHandler}
          beefId={beefIdSlove}
          refetch={refetch}
        />
      </RightContainer>
    </FlexContainer>
  );
};

export default memo(BeefPage);
